package givenchy

import java.text.*;

class TokenService {
    
    private static ENCODE_KEY = "www.yunso.cn/wanghe/romejiang"
    private static EXPIRE_HOUR = 3 // 密码失效时间 
    private static SimpleDateFormat fmt=new SimpleDateFormat( "yyyy/MM/dd/HH/mm");
    //static transactional = true
    // 权限验证和生成key的服务类，每小时都过期，需要再次获取
    def build(String info) {
        
        DESPlus plus = new DESPlus(ENCODE_KEY)

        
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, EXPIRE_HOUR) 
        return  plus.encrypt(info + "," + fmt.format(calendar.time));
   
    }
    //解码加密字符串
    def encode(String key) {
        try{
         DESPlus plus = new DESPlus(ENCODE_KEY)
         return  plus.decrypt(key);
         }catch(Exception  e){
            return null
         }
    }
    // 验证是否可用
    def  verify(String key){
        String decryptTxt = encode(key)
        if (decryptTxt != null) {
            Date last = fmt.parse(decryptTxt.substring(decryptTxt.indexOf(",")+1))
            return last.after(new Date()) 
        }
        return false

     }

     def user(String key){
        String decryptTxt = encode(key)
        log.info decryptTxt
        if (decryptTxt) {
            Long id = Long.parseLong(decryptTxt.substring(0,decryptTxt.indexOf(",")) )
            return User.get(id) 
        }
     }
}
